package com.roger.uia;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.util.Log;

import com.roger.uia.helper.UiBase;
import com.roger.uia.helper.util.FileUtils;
import com.roger.uia.helper.util.LogUtils;
import com.roger.uia.helper.util.StrUtils;
import com.roger.uia.helper.UiWatch;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import static com.roger.uia.helper.UiBase.mDevice;
import static com.roger.uia.helper.UiBase.waitTime;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestWifiComplex {
    private static final String TAG = TestWifiComplex.class.getSimpleName();

    @BeforeClass
    public static void beforeClass() throws Throwable {
        if(!mDevice.isScreenOn()) mDevice.wakeUp();
        mDevice.pressHome();
    }

    @Before
    public void setUp()  {
        Log.d(TAG,"-- set up --");
        FileUtils.getPermission();
        UiWatch.getWatcher().runErrorWatcher();
        UiWatch.getWatcher().runSpecialWatcher();
    }

    @After
    public void tearDown() {
        Log.d(TAG,"-- tear down --");
        UiWatch.getWatcher().removeErrorWatcher();
        UiWatch.getWatcher().removeSpecialWatcher();
    }

    @AfterClass
    public static void afterClass() throws Throwable {
        mDevice.pressHome();
    }

    @Test
    public void ComplexTest01_connectWifi(){
        Bundle para= InstrumentationRegistry.getArguments();
        String countryNow = para.getString("key");
        try {
            LogUtils.logcat(UiBase.filePath + "testWifi/logs/",countryNow + ".txt");
            try {
                skip_OOBE();
                //mDevice.executeShellCommand("settings put system screen_off_timeout 1800000");
                //mDevice.executeShellCommand("settings put global stay_on_while_plugged_in 3");
                //unLockScreen();
                //setScreenLockNone();
            }catch (Exception e){
                FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/pic/",countryNow+"_initDevice_error");
            }
            enterWLAN();
            connectWifiList(countryNow);
            //LogUtils.delLog(UiBase.filePath + "testWifi/logs/",countryNow + ".txt");
        }catch (Throwable e){
            FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/pic/",countryNow+"_startTest_error");
        }finally {
            LogUtils.stopLogCat();
            mDevice.pressHome();
        }
    }

    @Test
    public void ComplexTest02_switchCountry() throws Throwable {
//        String code = getCode(UiBase.filePath+"testWifi/code.txt").replaceAll("\n","");
//        Log.d(TAG,code);
        String list = "com.lenovo.EngineeringCode:id/country_list";
        Bundle para= InstrumentationRegistry.getArguments();
        String countryNext = para.getString("key");
        String deviceCode = mDevice.executeShellCommand("getprop ro.product.countrycode").replaceAll("\n","");
        Log.d(TAG,deviceCode+"->"+countryNext);
        if (!deviceCode.equals(countryNext) && countryNext != null)  {
            try{
                //create contacts
//                UiBase.openApp("com.android.contacts");
//                UiBase.waitClickObj(UiBase.objSelect[3],"com.android.contacts:id/floating_action_button",5);
//                UiBase.inputTxtToObj(UiBase.objSelect[0],"First name","Test");
//                UiBase.waitClickObj(UiBase.objSelect[0],"SAVE",3);
//                mDevice.pressBack();
//                if(!UiBase.existObj(UiBase.objSelect[3],"com.android.contacts:id/menu_search"))UiBase.openApp("com.android.contacts");
//                UiBase.waitClickObj(UiBase.objSelect[3],"com.android.contacts:id/menu_search",5);
//                UiBase.inputTxtToObj(UiBase.objSelect[0],"Search contacts",code);
//                UiBase.waitObjCheck(UiBase.objSelect[3],StrUtils.dialogView,3);
                UiBase.startApp("com.android.settings.intelligence/com.android.settings.intelligence.search.SearchActivity");
                UiBase.waitObj(UiBase.objSelect[3],"android:id/search_src_text",5);
                UiBase.inputTxtToObj(UiBase.objSelect[3],"android:id/search_src_text","####6030#");
                UiBase.waitObj(UiBase.objSelect[3],list,10);
                if(!UiBase.existObj(UiBase.objSelect[3],list)){
                    UiBase.inputTxtToObj(UiBase.objSelect[3],"android:id/search_src_text","####6020#");
                    UiBase.waitObj(UiBase.objSelect[3],list,3);
                }
                //select country code
                UiBase.scrollReidClickObj(list,UiBase.objSelect[2],countryNext.concat(" .*"));
                UiBase.waitClickObj(UiBase.objSelect[0],"OK",3);
                UiBase.waitClickObj(UiBase.objSelect[0],"OK",10);
                SystemClock.sleep(waitTime);
            }catch (Throwable e){
                FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/pic","fail_SwitchCC");
            }
        }
    }

    private void skip_OOBE()throws Throwable{
        String currentPackage = mDevice.getCurrentPackageName();
        Log.d(TAG,currentPackage);
        if(currentPackage.equals(StrUtils.oobe)){
            //refresh the screen
            mDevice.swipe(StrUtils.SCREEN_W/2,StrUtils.SCREEN_H, StrUtils.SCREEN_W/2, 0, 100);
            //set lang engUS
            UiBase.waitObj(UiBase.objSelect[0],StrUtils.englishUS,3);
            if(!UiBase.existObj(UiBase.objSelect[0],StrUtils.englishUS)){
                UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.langPick,3);
                UiBase.waitObj(UiBase.objSelect[3],StrUtils.dialogView,3);
                UiBase.scrollReidClickObj(StrUtils.dialogView,UiBase.objSelect[2],StrUtils.eng);
                UiBase.scrollReidClickObj(StrUtils.dialogView,UiBase.objSelect[2],StrUtils.usa);
            }
//            //Hi there
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.oobeStart,3);
//            //licence
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.setupMore,10);
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.setupNext,10);
//            //network
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.setupSkip,10);
//            //Wifi
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.setupSkip,10);
//            UiBase.waitObj(UiBase.objSelect[3],StrUtils.button1,3);
//            if(UiBase.existObj(UiBase.objSelect[3],StrUtils.button1)) UiBase.clickObj(UiBase.objSelect[3],StrUtils.button1);
//            //date&time
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.oobeNext,10);
//            //google service
//            UiBase.waitClickObj(UiBase.objSelect[0],"MORE",10);
//            UiBase.waitClickObj(UiBase.objSelect[0],"ACCEPT",10);
//            //lock
//            UiBase.waitClickObj(UiBase.objSelect[0],StrUtils.notNow,10);
//            UiBase.waitObj(UiBase.objSelect[3],StrUtils.button1,3);
//            if(UiBase.existObj(UiBase.objSelect[3],StrUtils.button1)) UiBase.clickObj(UiBase.objSelect[3],StrUtils.button1);
//            //face
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.faceSkip,10);
//            //ID
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.btnSkip,15);
//            //user experience
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.setupNext,10);
//            //navigation method
//            UiBase.waitClickObj(UiBase.objSelect[3],StrUtils.setupNext,15);
//            //finish
//            UiBase.waitObj(UiBase.objSelect[3],StrUtils.dockFinish,10);
//            if(UiBase.existObj(UiBase.objSelect[3],StrUtils.dockFinish)) UiBase.clickObj(UiBase.objSelect[3],StrUtils.dockFinish);
//            UiBase.waitObj(UiBase.objSelect[3],StrUtils.exitFinish,10);
//            if(UiBase.existObj(UiBase.objSelect[3],StrUtils.exitFinish)) UiBase.clickObj(UiBase.objSelect[3],StrUtils.exitFinish);
            SystemClock.sleep(waitTime * 3);
        }
    }

    private void unLockScreen() throws Throwable {
        if(!mDevice.isScreenOn()) mDevice.wakeUp();
        Log.d(TAG,mDevice.getCurrentPackageName());
        for(int i=0; i<10; i++){
            if(!mDevice.getCurrentPackageName().equals("com.android.systemui")) break;
            mDevice.swipe(mDevice.getDisplayWidth()/2, mDevice.getDisplayHeight()-100, mDevice.getDisplayWidth()/2, 100, 100);
            SystemClock.sleep(waitTime/2);
        }
        mDevice.pressHome();
    }

    private void setScreenLockNone() throws Throwable {
        UiBase.openApp(StrUtils.settingPac);
        UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingScroll,10);
        UiBase.scrollReidClickObj(StrUtils.settingScroll,UiBase.objSelect[2],StrUtils.settingSecurity);
        UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingList,3);
        if(UiBase.existObj(UiBase.objSelect[2],StrUtils.advanced)) UiBase.clickObj(UiBase.objSelect[2],StrUtils.advanced);
        UiBase.scrollReidClickObj(StrUtils.settingList,UiBase.objSelect[2],StrUtils.ScreenLock);
        UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.lockNone,3);
        mDevice.pressHome();
    }

    private void enterWLAN() throws Throwable {
        if (UiBase.existObj(UiBase.objSelect[2],StrUtils.wifi) && UiBase.existObj(UiBase.objSelect[3],StrUtils.frictionIcon)) {
            SystemClock.sleep(waitTime);
        } else {
            mDevice.pressHome();
            UiBase.openApp(StrUtils.settingPac);
            UiBase.waitObj(UiBase.objSelect[3],StrUtils.settingScroll,10);
            UiBase.scrollReidClickObj(StrUtils.settingScroll,UiBase.objSelect[2],StrUtils.settingNetwork);
            UiBase.waitClickObj(UiBase.objSelect[2],StrUtils.wifi,5);
            UiBase.waitObj(UiBase.objSelect[3],StrUtils.switch_widget,5);
            if (UiBase.getTxtFromObj(UiBase.objSelect[3],StrUtils.switch_widget).matches(StrUtils.off)) {
                UiBase.clickObj(UiBase.objSelect[3],StrUtils.switch_widget);
                SystemClock.sleep(waitTime * 10);
            }
            SystemClock.sleep(waitTime);
        }
    }

    private void connectWifiList(String country)throws Throwable{
        int rows=FileUtils.getTxtRows(UiBase.filePath+"testWifi/wifi.txt");
        Log.d(TAG,"All wifi num : " + rows);
        FileUtils.writeFile(UiBase.filePath + "testWifi/result/" + country + ".html",reportHead(country));
        for(int i=0;i<rows;i++){
            String wifiName = FileUtils.getTxt(UiBase.filePath+"testWifi/wifi.txt",i);
            String success="(?i)"+wifiName+",Connected.*|"+wifiName+",已连接.*";
            Log.d(TAG,"wifi name: "+wifiName);
            SystemClock.sleep(waitTime * 5);
            UiObject menuText = mDevice.findObject(new UiSelector().textMatches(wifiName));
            UiScrollable secMenuList = new UiScrollable(new UiSelector().resourceId(StrUtils.recycler));
            for(int j=0;j<3;j++){
                secMenuList.scrollIntoView(menuText);
                if(menuText.exists()) {
                    UiBase.scrollReidClickObj(StrUtils.recycler, UiBase.objSelect[2],wifiName);
                    SystemClock.sleep(waitTime);
                    for (int p = 0; p <= 30; p++) {
                        SystemClock.sleep(waitTime);
                        if (UiBase.existObj(UiBase.objSelect[6],success)) {
                            FileUtils.writeFile(UiBase.filePath + "testWifi/result/"+country + ".html",testResult(wifiName,"Pass"));
                            FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/pic/",country+"_"+wifiName+"_pass");
                            Log.d(TAG,"pass: "+ wifiName);
                            break;
                        }
                        if (p == 30) {
                            FileUtils.writeFile(UiBase.filePath + "testWifi/result/"+country + ".html",testResult(wifiName,"Fail"));
                            FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/pic/",country+"_"+wifiName+"_fail");
                            Log.d(TAG,"fail: "+ wifiName);
                        }
                    }
                    break;
                }else{
                    if(j == 2){
                        FileUtils.writeFile(UiBase.filePath + "testWifi/result/"+country + ".html",testResult(wifiName,"NA"));
                        FileUtils.takeScreenPicTo(UiBase.filePath+"testWifi/pic/",country+"_"+wifiName+"_NA");
                        Log.d(TAG,"NA: "+ wifiName);
                    }
                }
            }
        }
        FileUtils.writeFile(UiBase.filePath + "testWifi/result/"+country + ".html",reportEnd());
    }

    private String getCode(String path){
        String s ="";
        try {
            File file = new File(path);
            FileInputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is,"gbk"));
            String line = "";
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line);
            }
            s = stringBuilder.toString();
            br.close();
            is.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        return s;
    }

    private String reportHead(String country){
        String s ="<html>\n" +
                "<head>\n" +
                "<title>WIFI各国兼容性测试报告</title>\n" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n" +
                "</head>\n" +
                "<body> \n" +
                "<table border=\"1\" width=\"100%\" ALIGN=\"CENTER\" cellpadding=\"0\" cellspacing=\"0\" style=\"border-collapse:collapse\">\n" +
                "<th style=\"word-break:break-all;width:100%\"  ALIGN=\"CENTER\" background=\"#0f0f0f\" colspan=\"2\">"+"当前国家码："+country+"</th>\n" +
                "<tr style=\"word-break:break-all;background:#00BBFF\" ALIGN=\"CENTER\"><td style=\"width:60%\">WIFI名称</td><td style=\"width:40%\">连接结果</td></tr>";
        return s;
    }

    private String testResult(String wifiName, String result){
        String s="";
        switch (result) {
            case "Pass":
                s = "<tr><td style=\"word-break:break-all;width:60%\"  ALIGN=\"CENTER\">" + wifiName + "</td><td style=\"width:40%;color:#00FF00\"  ALIGN=\"CENTER\">Pass</td></tr>";
                break;
            case "NA":
                s = "<tr><td style=\"word-break:break-all;width:60%\"  ALIGN=\"CENTER\">" + wifiName + "</td><td style=\"width:40%;color:#FFFF00\"  ALIGN=\"CENTER\">NA</td></tr>";
                break;
            default:
                s = "<tr><td style=\"word-break:break-all;width:60%\"  ALIGN=\"CENTER\">" + wifiName + "</td><td style=\"width:40%;color:#FF0000\"  ALIGN=\"CENTER\">Fail</td></tr>";
                break;
        }
        return s;
    }

    private String reportEnd(){
        String s = "</table>\n" +
                "</body>\n" +
                "</html>\n";
        return s;
    }

}
